package com.qd.panda.func;

import com.cdqidi.util.IpHelper;
import com.qd.common.panda.domain.entity.func.ChannelFunDTO;
import com.qd.common.sys.domain.login.LoginUser;
import com.qd.panda.service.AsyncService;
import com.qd.panda.service.func.ChannelFunService;
import com.qd.system.service.person.AuthTokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;

/**
 * 渠道/APP_功能地址
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/app/channelFun/")
@Slf4j
public class AppChannelFunController {
    private final ChannelFunService channelFunService;
    private final AuthTokenService authTokenService;
    private final HttpServletRequest request;
    private final AsyncService asyncService;

    /**
     * 查看详情并记录
     *
     * @param funcId 功能ID
     * @return 记录
     */
    @GetMapping(value = "/getDetailAndAddLog")
    public ChannelFunDTO getDetailAndAddLog(@Validated @NotBlank(message = "功能不能为空") String funcId) {
        ChannelFunDTO channelFunDTO = channelFunService.getDetailAndAddLog(funcId);
        if (null != channelFunDTO) {
            String ipAddress = IpHelper.getIpAddress(request);
            LoginUser loginUser = authTokenService.getLoginUser(request);
            String userId = null;
            String mobile = null;
            if (null != loginUser) {
                userId = loginUser.getUserId();
                mobile = loginUser.getUser().getAppUserExtend().getMobile();
            }
            asyncService.addChannelScanLog(funcId, ipAddress, LocalDateTime.now(), userId, mobile);
        }
        return channelFunDTO;
    }
}